<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta name="keywords" content="SpringBoot2.x 单元测试, 闪烁之狐, Blinkfox">
    <meta name="description" content="
一个 bug 被隐藏的时间越长，修复这个 bug 的代价就越大。

我曾经在 单元测试指南 一文中写到过单元测试的必要性和 Java 单元测试相关的工具及方法。单元测试能帮助我们在早期就规避、发现和修复很多不易察觉的 bug 和漏洞，而且">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>SpringBoot2.x 单元测试 | 闪烁之狐</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
        code[class*="language-"], pre[class*="language-"] {
            white-space: pre !important;
        }
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">闪烁之狐</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">闪烁之狐</div>
        <div class="logo-desc">
            
            从来没有真正的绝境，只有心灵的迷途
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('http://static.blinkfox.com/20190302.png')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        SpringBoot2.x 单元测试
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }
</style>
<div class="row">
    <div class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/" target="_blank">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/单元测试/" target="_blank">
                                <span class="chip bg-color">单元测试</span>
                            </a>
                        
                            <a href="/tags/Spring/" target="_blank">
                                <span class="chip bg-color">Spring</span>
                            </a>
                        
                            <a href="/tags/SpringBoot/" target="_blank">
                                <span class="chip bg-color">SpringBoot</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/后端/" class="post-category" target="_blank">
                                后端
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-03-02
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        2.7k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        12 分
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>一个 bug 被隐藏的时间越长，修复这个 bug 的代价就越大。</p>
</blockquote>
<p>我曾经在 <a href="https://blinkfox.github.io/2018/11/15/hou-duan/java/dan-yuan-ce-shi-zhi-nan/">单元测试指南</a> 一文中写到过单元测试的必要性和 Java 单元测试相关的工具及方法。单元测试能帮助我们在早期就规避、发现和修复很多不易察觉的 bug 和漏洞，而且更能保障后期的需求变动和代码重构时所带来的隐患，减少测试成本和维护成本。在 SpringBoot2.x 集成和写单元测试更加容易了。</p>
<h2 id="创建-SpringBoot2-x-项目"><a href="#创建-SpringBoot2-x-项目" class="headerlink" title="创建 SpringBoot2.x 项目"></a>创建 SpringBoot2.x 项目</h2><p>在 <a href="https://start.spring.io/" target="_blank" rel="noopener">start.spring.io</a> 中创建一个自己的 SpringBoot2.x 项目，目前版本<code>2.1.3</code>。选出自己需要的一些组件生成项目即可，我这里选了如下几个：</p>
<ul>
<li><code>Web</code>: Web项目</li>
<li><code>JPA</code>: 数据库持久层采用<a href="https://spring.io/guides/gs/accessing-data-jpa/" target="_blank" rel="noopener">Spring Data JPA</a>，方便实用</li>
<li><code>Lombok</code>: 可以通过注解大量减少Java中重复代码的书写</li>
<li><code>HSQLDB</code>: 内存数据库，用来对 <code>Repository</code> 层做单元测试</li>
</ul>
<p>生成之后可以在 <code>pom.xml</code> 中看到 SpringBoot2.x 项目中已经引入了<code>spring-boot-starter-test</code>这个启动组件，包含了几乎绝大多数测试场景需要的组件。然后通过<code>mvn clean install</code>来构建本项目或者直接导入 IDE 开发工具即可。</p>
<p>下面将以对博客信息做简单修改和查询为示例来说明在 Spring Boot 中如何分别对 <code>DAO</code>，<code>Service</code>，<code>Controller</code> 做单元测试。</p>
<h2 id="DAO-层的单元测试"><a href="#DAO-层的单元测试" class="headerlink" title="DAO 层的单元测试"></a>DAO 层的单元测试</h2><h3 id="新建数据库脚本"><a href="#新建数据库脚本" class="headerlink" title="新建数据库脚本"></a>新建数据库脚本</h3><p>DAO 层的测试我这里采用的是 <code>HSQLDB</code> 的内存数据库，最好准备一些初始化的数据表结构和脚本，当然也可用直接通过官方示例的 <code>JPA</code>特性和 API 代码来初始化数据。这里我还是通过脚本的方式来做，便于统一管理和维护表结构和数据。</p>
<p>在 <code>src/test</code> 目录下新建 <code>resources</code> 资源目录，并在 <code>resources</code> 目录下新建 <code>db</code> 目录，在 <code>db</code> 目录下分别，新建用于管理的表结构文件(<code>schema.sql</code>)和初始化数据文件(<code>data.sql</code>)的 SQL 脚本。</p>
<p><code>schema.sql</code> 文件中的内容如下：</p>
<pre class=" language-sql"><code class="language-sql"><span class="token comment" spellcheck="true">-- 创建数据库表所在的模式 schema.</span>
<span class="token keyword">CREATE</span> <span class="token keyword">SCHEMA</span> test<span class="token punctuation">;</span>
<span class="token keyword">commit</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">-- 在 test 模式下创建数据库表.</span>
<span class="token keyword">DROP</span> <span class="token keyword">TABLE</span> <span class="token keyword">IF</span> <span class="token keyword">EXISTS</span> test<span class="token punctuation">.</span>t_test_blog<span class="token punctuation">;</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> test<span class="token punctuation">.</span>t_test_blog <span class="token punctuation">(</span>
    c_id <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    c_author <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    c_content <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    dt_publish_time <span class="token keyword">timestamp</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    c_title <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    c_url <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    n_status <span class="token keyword">int</span><span class="token punctuation">,</span>
    c_create_user <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    dt_create_time <span class="token keyword">timestamp</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    dt_update_time <span class="token keyword">timestamp</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token keyword">constraint</span> pk_test_blog <span class="token keyword">primary</span> <span class="token keyword">key</span><span class="token punctuation">(</span>c_id<span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">commit</span><span class="token punctuation">;</span></code></pre>
<p><code>data.sql</code> 文件中的内容如下：</p>
<pre class=" language-sql"><code class="language-sql"><span class="token comment" spellcheck="true">-- 初始化插入一些博客信息数据.</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> test<span class="token punctuation">.</span>t_test_blog <span class="token keyword">VALUES</span> <span class="token punctuation">(</span><span class="token string">'1'</span><span class="token punctuation">,</span> <span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token string">'这是内容'</span><span class="token punctuation">,</span> <span class="token string">'2019-03-01 00:41:01'</span><span class="token punctuation">,</span> <span class="token string">'Spring从入门到精通'</span><span class="token punctuation">,</span> 'https:<span class="token comment" spellcheck="true">//baidu.com', '1', 'tom', '2019-03-01 00:41:33', '2019-03-01 00:41:36');</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> test<span class="token punctuation">.</span>t_test_blog <span class="token keyword">VALUES</span> <span class="token punctuation">(</span><span class="token string">'2'</span><span class="token punctuation">,</span> <span class="token string">'李四'</span><span class="token punctuation">,</span> <span class="token string">'这是Mybatis的内容'</span><span class="token punctuation">,</span> <span class="token string">'2019-03-01 00:41:01'</span><span class="token punctuation">,</span> <span class="token string">'Mybatis基础'</span><span class="token punctuation">,</span> 'https:<span class="token comment" spellcheck="true">//qq.com', '2', 'jack', '2019-03-01 00:41:33', '2019-03-01 00:41:36');</span>
<span class="token keyword">commit</span><span class="token punctuation">;</span></code></pre>
<h3 id="增加-yaml-配置文件及内容"><a href="#增加-yaml-配置文件及内容" class="headerlink" title="增加 yaml 配置文件及内容"></a>增加 yaml 配置文件及内容</h3><p>在 <code>resources</code> 目录下新建 <code>application-hsqldb.yml</code> 配置文件，用于存放 HSQLDB 及 JPA 相关的配置信息，主要配置内容如下：</p>
<pre class=" language-yaml"><code class="language-yaml"><span class="token key atrule">spring</span><span class="token punctuation">:</span>
  <span class="token key atrule">datasource</span><span class="token punctuation">:</span>
    <span class="token key atrule">url</span><span class="token punctuation">:</span> jdbc<span class="token punctuation">:</span>hsqldb<span class="token punctuation">:</span>mem<span class="token punctuation">:</span>db_test <span class="token comment" spellcheck="true"># 以内存数据库的方式来运行.</span>
    <span class="token key atrule">username</span><span class="token punctuation">:</span> root
    <span class="token key atrule">password</span><span class="token punctuation">:</span> <span class="token number">123456</span>
    <span class="token key atrule">driver-class-name</span><span class="token punctuation">:</span> org.hsqldb.jdbc.JDBCDriver
    <span class="token key atrule">platform</span><span class="token punctuation">:</span> hsqldb
    <span class="token key atrule">schema</span><span class="token punctuation">:</span> classpath<span class="token punctuation">:</span>db/schema.sql
    <span class="token key atrule">data</span><span class="token punctuation">:</span> classpath<span class="token punctuation">:</span>db/data.sql
  <span class="token key atrule">jpa</span><span class="token punctuation">:</span>
    <span class="token key atrule">show-sql</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
    <span class="token key atrule">hibernate</span><span class="token punctuation">:</span>
      <span class="token key atrule">ddl-auto</span><span class="token punctuation">:</span> none <span class="token comment" spellcheck="true"># 这里没用 JPA 的自动生成表结构等功能，你可以视自己的具体情况来开启.</span>
    <span class="token key atrule">generate-ddl</span><span class="token punctuation">:</span> <span class="token boolean important">false </span><span class="token comment" spellcheck="true"># 启动时是否初始化数据库.</span></code></pre>
<h3 id="准备实体-POJO-和-DAO-层-Repository-类"><a href="#准备实体-POJO-和-DAO-层-Repository-类" class="headerlink" title="准备实体 POJO 和 DAO 层 Repository 类"></a>准备实体 POJO 和 DAO 层 Repository 类</h3><p>博客信息的实体 POJO 类如下：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Date<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>persistence<span class="token punctuation">.</span>Column<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>persistence<span class="token punctuation">.</span>Entity<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>persistence<span class="token punctuation">.</span>Id<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>persistence<span class="token punctuation">.</span>Table<span class="token punctuation">;</span>

<span class="token keyword">import</span> lombok<span class="token punctuation">.</span>Getter<span class="token punctuation">;</span>
<span class="token keyword">import</span> lombok<span class="token punctuation">.</span>Setter<span class="token punctuation">;</span>
<span class="token keyword">import</span> lombok<span class="token punctuation">.</span>experimental<span class="token punctuation">.</span>Accessors<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * 博客实体.
 *
 * @author blinkfox on 2019-2-26.
 */</span>
<span class="token annotation punctuation">@Getter</span>
<span class="token annotation punctuation">@Setter</span>
<span class="token annotation punctuation">@Accessors</span><span class="token punctuation">(</span>chain <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Entity</span>
<span class="token annotation punctuation">@Table</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"t_test_blog"</span><span class="token punctuation">,</span> schema <span class="token operator">=</span> <span class="token string">"test"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Blog</span> <span class="token punctuation">{</span>

    <span class="token comment" spellcheck="true">/**
     * ID.
     */</span>
    <span class="token annotation punctuation">@Id</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_id"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String id<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 作者.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_author"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String author<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 标题.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_title"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String title<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 内容.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_content"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String content<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 发布时间.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"dt_publish_time"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> Date publishTime<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 链接地址.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_url"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String url<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 状态.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"n_status"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> Integer status<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 创建用户.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"c_create_user"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> String createUser<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 创建时间.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"dt_create_time"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> Date createTime<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 最后更新时间.
     */</span>
    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"dt_update_time"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> Date updateTime<span class="token punctuation">;</span>

<span class="token punctuation">}</span></code></pre>
<p>下面是 <code>BlogRepository</code> 中的一个简单的自定义 <code>@Query</code> 查询，当然你也可以采用名称的规则来写本查询，我这里为了做示例，使用了 <code>@Query</code> 查询。</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>repository<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">.</span>Blog<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>data<span class="token punctuation">.</span>jpa<span class="token punctuation">.</span>repository<span class="token punctuation">.</span>JpaRepository<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>data<span class="token punctuation">.</span>jpa<span class="token punctuation">.</span>repository<span class="token punctuation">.</span>Query<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>stereotype<span class="token punctuation">.</span>Repository<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogRepository.
 *
 * @author blinkfox on 2019-02-27.
 */</span>
<span class="token annotation punctuation">@Repository</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">BlogRepository</span> <span class="token keyword">extends</span> <span class="token class-name">JpaRepository</span><span class="token operator">&lt;</span>Blog<span class="token punctuation">,</span> String<span class="token operator">></span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Query</span><span class="token punctuation">(</span><span class="token string">"SELECT b FROM Blog AS b WHERE b.title like 'Spring%'"</span><span class="token punctuation">)</span>
    List<span class="token operator">&lt;</span>Blog<span class="token operator">></span> <span class="token function">querySpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span></code></pre>
<h3 id="BlogRepository-的单元测试"><a href="#BlogRepository-的单元测试" class="headerlink" title="BlogRepository 的单元测试"></a>BlogRepository 的单元测试</h3><p>然后在 Intellij IDEA 中通过 <code>Ctrl + Shift + T</code> 来为 <code>BlogRepository</code> 生成它对应的单元测试类 <code>BlogRepositoryTest</code>。</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>repository<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">.</span>Blog<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Optional<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>Resource<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>Assert<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>Test<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>runner<span class="token punctuation">.</span>RunWith<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>test<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>orm<span class="token punctuation">.</span>jpa<span class="token punctuation">.</span>DataJpaTest<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>context<span class="token punctuation">.</span>ActiveProfiles<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>context<span class="token punctuation">.</span>junit4<span class="token punctuation">.</span>SpringRunner<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogRepositoryTest.
 *
 * @author blinkfox on 2019-03-01.
 */</span>
<span class="token annotation punctuation">@RunWith</span><span class="token punctuation">(</span>SpringRunner<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@ActiveProfiles</span><span class="token punctuation">(</span><span class="token string">"hsqldb"</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@DataJpaTest</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BlogRepositoryTest</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> BlogRepository blogRepository<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 测试新增博客的情况.
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">save</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        String id <span class="token operator">=</span> <span class="token string">"newblogId"</span><span class="token punctuation">;</span>
        String title <span class="token operator">=</span> <span class="token string">"Java 从入门到放弃"</span><span class="token punctuation">;</span>
        blogRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Blog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setTitle</span><span class="token punctuation">(</span>title<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        Optional<span class="token operator">&lt;</span>Blog<span class="token operator">></span> blogOptional <span class="token operator">=</span> blogRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        Assert<span class="token punctuation">.</span><span class="token function">assertTrue</span><span class="token punctuation">(</span>blogOptional<span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> title<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>blogOptional<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getTitle</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 测试查询所有 Spring 相关的博客信息.
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">querySpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        List<span class="token operator">&lt;</span>Blog<span class="token operator">></span> blogs <span class="token operator">=</span> blogRepository<span class="token punctuation">.</span><span class="token function">querySpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Assert<span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> blogs<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Assert<span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">"Spring从入门到精通"</span><span class="token punctuation">,</span> blogs<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getTitle</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<p>这样就完成了 DAO 层代码的测试，以上程序主要依托于内存数据库 HSQLDB 和 Spring Data JPA。</p>
<h2 id="Service-层的单元测试"><a href="#Service-层的单元测试" class="headerlink" title="Service 层的单元测试"></a>Service 层的单元测试</h2><p>实际开发过程中，Service 层中的类依赖了 DAO 层中的类或其他 Service 类。为了隔离对其他 Service 类或 DAO 层中的类的依赖，只测试本 Service 类中的方法逻辑，就需要 Mock 数据和做打桩等操作。Spring Boot 中原生集成了 <a href="https://site.mockito.org/" target="_blank" rel="noopener">Mockito</a>，可以非常方便我们对 Java 代码做单元测试。</p>
<h3 id="新建-BlogService-类"><a href="#新建-BlogService-类" class="headerlink" title="新建 BlogService 类"></a>新建 BlogService 类</h3><pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>service<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">.</span>Blog<span class="token punctuation">;</span>
<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>repository<span class="token punctuation">.</span>BlogRepository<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Optional<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>Resource<span class="token punctuation">;</span>

<span class="token keyword">import</span> lombok<span class="token punctuation">.</span>extern<span class="token punctuation">.</span>slf4j<span class="token punctuation">.</span>Slf4j<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>stereotype<span class="token punctuation">.</span>Service<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogService.
 *
 * @author blinkfox on 2019-03-01.
 */</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token annotation punctuation">@Service</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BlogService</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> BlogRepository blogRepository<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 查询所有 Spring 相关的博客信息.
     *
     * @return 博客信息
     */</span>
    <span class="token keyword">public</span> List<span class="token operator">&lt;</span>Blog<span class="token operator">></span> <span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"进入了获取 Spring 相关博客的 Service 方法."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> blogRepository<span class="token punctuation">.</span><span class="token function">querySpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 根据博客ID来修改该博客的名称.
     *
     * @param id 博客ID
     * @param title 博客标题
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">modifyTitileById</span><span class="token punctuation">(</span>String id<span class="token punctuation">,</span> String title<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        Optional<span class="token operator">&lt;</span>Blog<span class="token operator">></span> blogOptional <span class="token operator">=</span> blogRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>blogOptional<span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"需要修改名称的博客不存在，id为【{}】请检查！"</span><span class="token punctuation">,</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        blogRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>blogOptional<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setTitle</span><span class="token punctuation">(</span>title<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<h3 id="BlogService-的单元测试"><a href="#BlogService-的单元测试" class="headerlink" title="BlogService 的单元测试"></a>BlogService 的单元测试</h3><p>通过 <code>BlogService</code> 可以生成和书写出其对应的单元测试类和测试方法，代码如下：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>service<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">.</span>Blog<span class="token punctuation">;</span>
<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>repository<span class="token punctuation">.</span>BlogRepository<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>ArrayList<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Optional<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>Assert<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>Test<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>runner<span class="token punctuation">.</span>RunWith<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>InjectMocks<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>Mock<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>Mockito<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>MockitoJUnitRunner<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogServiceTest.
 *
 * @author blinkfox on 2019-03-01.
 */</span>
<span class="token annotation punctuation">@RunWith</span><span class="token punctuation">(</span>MockitoJUnitRunner<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BlogServiceTest</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Mock</span>
    <span class="token keyword">private</span> BlogRepository blogRepository<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@InjectMocks</span>
    <span class="token keyword">private</span> BlogService blogService<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 测试service层中获取Spring相关博客的方法.
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 构造需要返回的博客信息集合数据.</span>
        Blog blog <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Blog</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">setTitle</span><span class="token punctuation">(</span><span class="token string">"Spring Action"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        List<span class="token operator">&lt;</span>Blog<span class="token operator">></span> blogList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        blogList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>blog<span class="token punctuation">)</span><span class="token punctuation">;</span>

        Mockito<span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">.</span><span class="token function">querySpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span>blogList<span class="token punctuation">)</span><span class="token punctuation">;</span>
        List<span class="token operator">&lt;</span>Blog<span class="token operator">></span> blogs <span class="token operator">=</span> blogService<span class="token punctuation">.</span><span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 断言验证查询到的数据.</span>
        Assert<span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> blogs<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Assert<span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">"Spring Action"</span><span class="token punctuation">,</span> blog<span class="token punctuation">.</span><span class="token function">getTitle</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 测试根据博客ID来修改该博客的名称成功时的情况.
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">modifyTitileById</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// Mock 相关数据和类方法的行为.</span>
        String id <span class="token operator">=</span> <span class="token string">"1"</span><span class="token punctuation">;</span>
        Mockito<span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span>Optional<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Blog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Mockito<span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>Mockito<span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Blog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        blogService<span class="token punctuation">.</span><span class="token function">modifyTitileById</span><span class="token punctuation">(</span>id<span class="token punctuation">,</span> <span class="token string">"算法导论"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 验证 blogRepository.save(s) 方法被调用过一次.</span>
        Mockito<span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>Mockito<span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 测试根据博客ID来修改该博客的名称失败时的情况.
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">modifyTitileByIdWithFailure</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// Mock 未根据 ID 找到对应的博客信息的情况.</span>
        String id <span class="token operator">=</span> <span class="token string">"1"</span><span class="token punctuation">;</span>
        Mockito<span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span>Optional<span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>null<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        blogService<span class="token punctuation">.</span><span class="token function">modifyTitileById</span><span class="token punctuation">(</span>id<span class="token punctuation">,</span> <span class="token string">"算法导论"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 验证 blogRepository.save(s) 方法并没有被调用过.</span>
        Mockito<span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>blogRepository<span class="token punctuation">,</span> Mockito<span class="token punctuation">.</span><span class="token function">never</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>Mockito<span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<blockquote>
<p><strong>注意</strong>：这里的 <code>@RunWith</code> 采用的是 Mocktio 提供的 <code>MockitoJUnitRunner</code>。</p>
</blockquote>
<p>这样就完成了 Service 层的单元测试，也是我们业务开发中需要重点关注和测试业务逻辑的一层。</p>
<h2 id="Controller-层的单元测试"><a href="#Controller-层的单元测试" class="headerlink" title="Controller 层的单元测试"></a>Controller 层的单元测试</h2><p>Controller 层测试的重点是测试接口是否能正常工作。可以用到 Spring Boot 中提供的 <code>@WebMvcTest</code> 注解来模拟 Web 层的单元测试。当然，也需要通过 Mock 的方式类隔离对 Service 层各个类的依赖影响。</p>
<h3 id="新建-BlogController-类"><a href="#新建-BlogController-类" class="headerlink" title="新建 BlogController 类"></a>新建 BlogController 类</h3><pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>controller<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>pojo<span class="token punctuation">.</span>Blog<span class="token punctuation">;</span>
<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>service<span class="token punctuation">.</span>BlogService<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>Resource<span class="token punctuation">;</span>

<span class="token keyword">import</span> lombok<span class="token punctuation">.</span>extern<span class="token punctuation">.</span>slf4j<span class="token punctuation">.</span>Slf4j<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>http<span class="token punctuation">.</span>HttpStatus<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>http<span class="token punctuation">.</span>ResponseEntity<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>GetMapping<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>PatchMapping<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>PathVariable<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>RequestMapping<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>RequestParam<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>web<span class="token punctuation">.</span>bind<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>RestController<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogController.
 *
 * @author blinkfox on 2019-02-28.
 */</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token string">"/blogs"</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BlogController</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> BlogService blogService<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 获取所有 Spring 相关的博客信息.
     *
     * @return Spring相关的博客信息
     */</span>
    <span class="token annotation punctuation">@GetMapping</span>
    <span class="token keyword">public</span> ResponseEntity<span class="token operator">&lt;</span>List<span class="token operator">&lt;</span>Blog<span class="token operator">>></span> <span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> ResponseEntity<span class="token punctuation">.</span><span class="token function">ok</span><span class="token punctuation">(</span>blogService<span class="token punctuation">.</span><span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 根据博客ID修改博客名称.
     *
     * @param id 博客ID
     * @param title 博客标题
     * @return 空
     */</span>
    <span class="token annotation punctuation">@PatchMapping</span><span class="token punctuation">(</span><span class="token string">"/{id}"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> ResponseEntity<span class="token operator">&lt;</span>Void<span class="token operator">></span> <span class="token function">modifyTitileById</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span> String id<span class="token punctuation">,</span>
            <span class="token annotation punctuation">@RequestParam</span><span class="token punctuation">(</span><span class="token string">"title"</span><span class="token punctuation">)</span> String title<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            blogService<span class="token punctuation">.</span><span class="token function">modifyTitileById</span><span class="token punctuation">(</span>id<span class="token punctuation">,</span> title<span class="token punctuation">)</span><span class="token punctuation">;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"修改博客名称成功."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ResponseEntity</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span>HttpStatus<span class="token punctuation">.</span>OK<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"修改博客名称出错，id为【{}】."</span><span class="token punctuation">,</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ResponseEntity</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span>HttpStatus<span class="token punctuation">.</span>INTERNAL_SERVER_ERROR<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<h3 id="BlogController-的单元测试"><a href="#BlogController-的单元测试" class="headerlink" title="BlogController 的单元测试"></a>BlogController 的单元测试</h3><p>通过 <code>BlogController</code> 可以生成和书写出其对应的单元测试类和测试方法，代码如下：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>controller<span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token keyword">static</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>request<span class="token punctuation">.</span>MockMvcRequestBuilders<span class="token punctuation">.</span>get<span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token keyword">static</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>request<span class="token punctuation">.</span>MockMvcRequestBuilders<span class="token punctuation">.</span>patch<span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token keyword">static</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>result<span class="token punctuation">.</span>MockMvcResultMatchers<span class="token punctuation">.</span>status<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>blinkfox<span class="token punctuation">.</span>springbootsample<span class="token punctuation">.</span>service<span class="token punctuation">.</span>BlogService<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>ArrayList<span class="token punctuation">;</span>
<span class="token keyword">import</span> javax<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span>Resource<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>Test<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>junit<span class="token punctuation">.</span>runner<span class="token punctuation">.</span>RunWith<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>Mockito<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>test<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>WebMvcTest<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>test<span class="token punctuation">.</span>mock<span class="token punctuation">.</span>mockito<span class="token punctuation">.</span>MockBean<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>context<span class="token punctuation">.</span>junit4<span class="token punctuation">.</span>SpringRunner<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>test<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>MockMvc<span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/**
 * BlogControllerTest.
 *
 * @author blinkfox on 2019-03-02.
 */</span>
<span class="token annotation punctuation">@RunWith</span><span class="token punctuation">(</span>SpringRunner<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@WebMvcTest</span><span class="token punctuation">(</span>BlogController<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BlogControllerTest</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> MockMvc mockMvc<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@MockBean</span>
    <span class="token keyword">private</span> BlogService blogService<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * 测试获取所有 Spring 相关的博客信息.
     *
     * @throws Exception 异常
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        Mockito<span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogService<span class="token punctuation">.</span><span class="token function">getSpringBlogs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>mockMvc<span class="token punctuation">.</span><span class="token function">perform</span><span class="token punctuation">(</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"/blogs"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">andExpect</span><span class="token punctuation">(</span><span class="token function">status</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isOk</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 测试修改博客标题成功时的情况.
     *
     * @throws Exception 异常
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">modifyTitileById</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        Mockito<span class="token punctuation">.</span><span class="token function">doNothing</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogService<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">modifyTitileById</span><span class="token punctuation">(</span>Mockito<span class="token punctuation">.</span><span class="token function">anyString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> Mockito<span class="token punctuation">.</span><span class="token function">anyString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>mockMvc<span class="token punctuation">.</span><span class="token function">perform</span><span class="token punctuation">(</span><span class="token function">patch</span><span class="token punctuation">(</span><span class="token string">"/blogs/1?title=Spring实战"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">andExpect</span><span class="token punctuation">(</span><span class="token function">status</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isOk</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/**
     * 测试修改博客标题失败时的情况.
     *
     * @throws Exception 异常
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">modifyTitileByIdWithException</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        Mockito<span class="token punctuation">.</span><span class="token function">doThrow</span><span class="token punctuation">(</span>RuntimeException<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>blogService<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">modifyTitileById</span><span class="token punctuation">(</span>Mockito<span class="token punctuation">.</span><span class="token function">anyString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> Mockito<span class="token punctuation">.</span><span class="token function">anyString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>mockMvc<span class="token punctuation">.</span><span class="token function">perform</span><span class="token punctuation">(</span><span class="token function">patch</span><span class="token punctuation">(</span><span class="token string">"/blogs/1?title=Spring实战"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">andExpect</span><span class="token punctuation">(</span><span class="token function">status</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">is5xxServerError</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<p>以上就完成了对 Controller 层的单元测试。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>在 Spring Boot 中做单元测试的将会非常容易。上面只是 Spring Boot 中提供的部分方式，<a href="https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#boot-features-testing" target="_blank" rel="noopener">Spring Boot 文档</a> 中还有其他更多的测试场景和测试方法供你去参考和使用。</p>

            </div>
            <hr/>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            <div class="reprint">
                <p>
                    <span class="reprint-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="https://blinkfox.github.io" class="b-link-green">闪烁之狐</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/03/02/hou-duan/spring/springboot2.x-dan-yuan-ce-shi/" class="b-link-green">SpringBoot2.x 单元测试</a>
                </p>
            </div>
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: '2e56c9f3a90b6e8fb4f0',
        clientSecret: 'ba491ea79bbff85ec80b88db79e210b474a9cbc8',
        repo: 'blinkfox.github.io',
        owner: 'blinkfox',
        admin: ["blinkfox"],
        id: '2019-03-02T17-20-00',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/08/20/hou-duan/jpa/fenix-bi-mybatis-geng-jia-qiang-da-de-spring-data-jpa-kuo-zhan-ku/">
                    <div class="card-image">
                        
                        <img src="http://static.blinkfox.com/blog/2019/08/20jpa-20190820.png" class="responsive-img" alt="Fenix — 比 MyBatis 更加强大的 Spring Data JPA 扩展库">
                        
                        <span class="card-title">Fenix — 比 MyBatis 更加强大的 Spring Data JPA 扩展库</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary">
Fenix（菲尼克斯）是一个比 MyBatis 更加强大，为解决复杂、动态 SQL (JPQL) 而生的 Spring Data JPA 扩展库，目的是辅助开发者更方便、快捷的书写复杂、动态且易于维护的 SQL，支持 XML 和 Java</div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-08-20
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/后端/" class="post-category" target="_blank">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/" target="_blank">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/JPA/" target="_blank">
                        <span class="chip bg-color">JPA</span>
                    </a>
                    
                    <a href="/tags/Fenix/" target="_blank">
                        <span class="chip bg-color">Fenix</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/02/14/hou-duan/java/java-dai-ma-xing-neng-ping-gu-ku-stalker-jie-shao/">
                    <div class="card-image">
                        
                        <img src="http://static.blinkfox.com/2019-02-14.jpg" class="responsive-img" alt="Java代码性能评估库Stalker介绍">
                        
                        <span class="card-title">Java代码性能评估库Stalker介绍</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary">English Document

这是一个简单的用来对Java代码做性能评估的工具库。

特性
轻量级（jar包仅26kb）
API简单易用
易于集成或扩展

Maven集成&lt;dependency>
    &lt;groupId></div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-02-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/后端/" class="post-category" target="_blank">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/" target="_blank">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/性能测试/" target="_blank">
                        <span class="chip bg-color">性能测试</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


    </div>
    <div class="col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站由&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题搭建.

            
                &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
                <span class="white-color">194.7k</span>
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox/" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:chenjiayin1990@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1181062873" class="tooltipped" data-tooltip="QQ联系我: 1181062873" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>